package com.origin.baselibrary.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

// registerForActivityResult方法介绍以及封装
public class ActivityResultFragment extends Fragment {
    private ActivityResultCallback<ActivityResult> mCallback;
    private Intent mIntent;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityResultLauncher<Intent> activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            Log.e("ActivityResultFragment", "====>");
            if (mCallback != null) {
                mCallback.onActivityResult(result);
            }
            getParentFragmentManager().beginTransaction()
                    .remove(ActivityResultFragment.this)
                    .commitAllowingStateLoss();

        });
        if (mIntent != null) {
            activityResultLauncher.launch(mIntent);
        }
    }

    public static void launchActivityResult(FragmentManager fragmentManager, Intent intent, ActivityResultCallback<ActivityResult> callback) {
        ActivityResultFragment fragment = new ActivityResultFragment();
        fragment.setCallback(callback);
        fragment.setIntent(intent);
        fragmentManager.beginTransaction()
                .add(fragment, "ActivityResultFragment")
                .commitAllowingStateLoss();
    }

    private void setIntent(Intent intent) {
        mIntent = intent;
    }

    private void setCallback(ActivityResultCallback<ActivityResult> callback) {
        mCallback = callback;
    }

    @Override
    public void onDestroy() {
        mCallback = null;
        super.onDestroy();
    }
}
